#include <iostream>
#include <stdio.h>
#include <mysql/mysql.h>
#include <string>
#include <unistd.h>

using namespace std;
static const char* host = "127.0.0.1";
static const char* user = "pig";
static const char* pwd = "123456";
static const char* db = "testdb";
static const  unsigned int port = 3306;

int main()
{
    // 返回值变量
    MYSQL* r1 = nullptr;
    int r2 = 0;
    // 初始化
    MYSQL* my = mysql_init(nullptr);

    // 连接数据库
    r1 = mysql_real_connect(my, host, user, pwd, db, port, nullptr, 0);

    if(r1 == nullptr) {
        cerr << "连接失败!" << endl;
        return 1;
    } 

    cout << "连接成功!\n"; 

    // 设置字符集
    r2 = mysql_set_character_set(my, "utf8");

    if(r2 != 0) {
        cerr << "设置字符集失败\n";
        return 2;
    }

    // 执行sql语句
    const char* query = "select * from t1";
    r2 = mysql_query(my, query);

    if(r2 != 0) {
        cerr << "执行sql失败!\n";
        return 3;
    }

    // 获取结果集
    MYSQL_RES* res = mysql_store_result(my);

    if(res == nullptr) {
        cerr << "获取结果集失败!\n";
        return 4;
    }

    // 获得行和列
    my_ulonglong row = mysql_num_rows(res);
    unsigned int col = mysql_num_fields(res);

    // 获取结果集的属性，这里主要是获取列名
    MYSQL_FIELD* propertyArray = mysql_fetch_fields(res);
    for(int i = 0; i < col; ++i) {
        cout << propertyArray[i].name << '\t';
    }

    cout << '\n';
    cout << propertyArray[0].table << '\t' << propertyArray[0].db << '\n';

    // 循环获取结果集内容
    for(int i = 0; i < row; ++i) {
        MYSQL_ROW array = mysql_fetch_row(res);
        for(int j = 0; j < col; ++j) {
            cout << array[j] << '\t';
        }
        cout << '\n';
    }

    cout << "执行sql语句成功!\n";
    // 关闭连接
    mysql_close(my);
    return 0;
}